﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Globalization;

namespace VSM
{
    public partial class GoodsReceiptPO : System.Web.UI.Page
    {
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private static DataTable dtWhs;
        private static DataTable dtOpt;
        private static GeneralFunctions GF = null;
        private string TblHeaderName = "OPDN";
        private string TblLineName = "PDN1";
        private string CurrentPageUrl = "/Business/Purchasing/GoodsReceiptPO.aspx";
        private string HeaderKeyName = "DocEntry";
        private String TargetPageUrl = "/Business/Purchasing/APInvoice.aspx";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }
                if (!IsPostBack)
                {
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    ClearScreen();

                    // Load Warehouse
                    dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.SALES);
                    // Load Option Code
                    dtOpt = GF.GetMasterListBySqlCommand(dbType, "select * from [@OPTIONCODE] ");

                    String grpoId = Request.QueryString["grpo_id"];
                    if (!String.IsNullOrEmpty(grpoId))
                    {
                        LoadData(grpoId, ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO));
                        if (lblStatus.Text == "Closed")
                            SetScreenStatus("Close");
                        else if (lblStatus.Text == "O")
                            SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }

                    String BaseEntry = Request.QueryString["base_entry"];
                    if (!String.IsNullOrEmpty(BaseEntry))
                    {
                        String BaseType = Request.QueryString["base_type"];
                        LoadData(BaseEntry, BaseType);
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvGRPO.PageIndex = e.NewPageIndex;
            DataTable tblPDN1 = (DataTable)Session["PDN1Table"];
            BindData(tblPDN1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["PDN1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        }
                        tb.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tb.Rows) // reset detail No. line
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvGRPO.EditIndex = -1;
                    BindData((DataTable)Session["PDN1Table"]);
                    CalcTotal(((DataTable)Session["PDN1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                //
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label lblModel = (Label)e.Row.FindControl("lblModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (lblModel != null) ddlModel.SelectedValue = lblModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, lblModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label lblProduct = (Label)e.Row.FindControl("lblProduct");
                    if (lblProduct != null) ddlProduct.SelectedValue = lblProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label lblColor = (Label)e.Row.FindControl("lblColor");
                    if (lblColor != null) ddlColor.SelectedValue = lblColor.Text;
                }

                // Load Option Code
                DropDownList ddlOpt = (DropDownList)e.Row.FindControl("ddlOpt");
                if (ddlOpt != null)
                {
                    ddlOpt.DataSource = dtOpt;
                    ddlOpt.DataValueField = "Code";
                    ddlOpt.DataTextField = "Name";
                    ddlOpt.DataBind();
                    ddlOpt.Items.Insert(0, "");
                    HiddenField hdnOpt = (HiddenField)e.Row.FindControl("hdnOpt");
                    if (hdnOpt != null) ddlOpt.SelectedValue = hdnOpt.Value;
                }

                // Load Whs
                DropDownList ddlWhs = (DropDownList)e.Row.FindControl("ddlWhs");
                if (ddlWhs != null)
                {
                    ddlWhs.DataSource = dtWhs;
                    ddlWhs.DataValueField = "WhsCode";
                    ddlWhs.DataTextField = "WhsName";
                    ddlWhs.DataBind();
                    HiddenField hdnWhsCode = (HiddenField)e.Row.FindControl("hdnWhsCode");
                    if (hdnWhsCode != null) ddlWhs.SelectedValue = hdnWhsCode.Value;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PDN1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                this.grvGRPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /*protected void txtDistNumber_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDistNumber = (TextBox)row.FindControl("txtDistNumber");

                if (txtDistNumber.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input VIN Number');", true);
                    txtDistNumber.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PDN1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DistNumber"] = txtDistNumber.Text.Trim();
                        rupdate[0]["InDate"] = txtPostingDate.Text;
                        //rupdate[0]["Notext"] = txtPostingDate.Text;
                    }
                }

                this.grvGRPO.EditIndex = -1;
                BindData(tb);            
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }*/

        /*protected void txtEngineNumber_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtEngineNumber = (TextBox)row.FindControl("txtEngineNumber");

                if (txtEngineNumber.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Engine Number');", true);
                    txtEngineNumber.Focus();
                    return;
                }

                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PDN1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0) rupdate[0]["Notes"] = txtEngineNumber.Text.Trim();
                }

                this.grvGRPO.EditIndex = -1;
                BindData(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }        
        }*/

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Unit Price');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PDN1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvGRPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        //protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        this.lblError.Visible = false;
        //        GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
        //        ViewState["rowindex"] = row.RowIndex;
        //        TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
        //        if (txtDiscPrcnt.Text.Trim().Length == 0)
        //        {
        //            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
        //            txtDiscPrcnt.Focus();
        //            return;
        //        }
        //        Label lblItemCode = (Label)row.FindControl("lblItemCode");

        //        DataTable tb = (DataTable)Session["PDN1Table"];
        //        if (tb != null)
        //        {
        //            DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
        //            if (rupdate.Length > 0)
        //            {
        //                rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
        //                updateRowTotalPrice(rupdate[0], "DiscPrcnt");
        //            }
        //        }

        //        this.grvGRPO.EditIndex = -1;

        //        BindData(tb);
        //        CalcTotal(tb);
        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        //private DataRow FillShipToAddress(string outletId, bool isFill)
        //{
        //    try
        //    {
        //        if (outletId.Length > 0)
        //        {
        //            MasterData obj = new MasterData();
        //            DataSet tbWareHouse = null; // obj.GetWareHouseAddress(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode);
        //            if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
        //            {

        //                DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
        //                if (r.Length > 0)
        //                {
        //                    if (isFill)
        //                    {
        //                        StringBuilder shipTo = new StringBuilder();
        //                        shipTo.AppendLine(r[0]["Block"].ToString());
        //                        shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
        //                        shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
        //                    }
        //                    else
        //                    {
        //                        return r[0];
        //                    }
        //                }
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        this.lblError.Text = ex.Message;
        //        this.lblError.Visible = true;
        //    }
        //    return null;
        //}

        private void BindData(DataTable tblData)
        {
            Session["PDN1Table"] = tblData;
            this.grvGRPO.DataSource = tblData;
            this.grvGRPO.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
                    DataTable tblPDN1 = (DataTable)Session["PDN1Table"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblPDN1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblPDN1.NewRow();
                                        rowNew["No"] = (tblPDN1.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] =
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        //rowNew["PriceBefDi"] = 0;
                                        //rowNew["DiscPrcnt"] = 0;
                                        rowNew["PriceBefDi"] = 0;
                                        rowNew["TaxCode"] = "";
                                        rowNew["VatPrcnt"] = 0;
                                        rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                                        rowNew["U_OptionCode"] = string.Empty;
                                        tblPDN1.Rows.Add(rowNew);
                                    }

                                    if (tblPDN1.Rows.Count > 0)
                                    {
                                        //Update Price
                                        foreach (DataRow dr in tblPDN1.Rows)
                                            updateRowTotalPrice(dr, "");
                                        CalcTotal(tblPDN1);
                                    }
                                    //ReLoad Data
                                    //BindData(tblPOR1);
                                }
                            }
                            //ReLoad Data
                            BindData(tblPDN1);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtVendorCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtVendorName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            if (tblPDN1 != null)
                            {
                                tblPDN1.Rows.Clear();
                            }
                            Session["ChosenBP"] = null;
                            //tblPOR1 = LoadSetupItem(poDate, tblPOR1);
                            //LoadSupplierAmount();
                            this.btnAddItems.Visible = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string poId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(poId, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void UpdatePrice()
        {
            try
            {
                //Update Price
                foreach (DataRow r in ((DataTable)Session["PDN1Table"]).Rows)
                {
                    GetPrice(r);
                }
                BindData((DataTable)Session["PDN1Table"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// Update Price
        /// </summary>
        /// <param name="r"></param>
        private void GetPrice(DataRow r)
        {
            try
            {
                DataSet ds = GetDataItem( DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblIPO"></param>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="itemName"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataTable AddNewItem(DataTable tblPO, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color)
        {
            try
            {
                if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
                {
                    DataRow rowNew = tblPO.NewRow();
                    rowNew["ItemCode"] = ItemCode;
                    rowNew["Dscription"] = Dscription;
                    rowNew["U_Model"] = Model;
                    rowNew["U_Color"] = Color;
                    rowNew["Quantity"] = 1;

                    rowNew["PriceBefDi"] = drDefaultLine["UnitPrice"];
                    //rowNew["DiscPrcnt"] = drDefaultLine["Discount"];
                    rowNew["Price"] = drDefaultLine["UnitPrice"];

                    rowNew["TaxCode"] = drDefaultLine["TaxCode"];
                    rowNew["VatPrcnt"] = drDefaultLine["TaxRate"];

                    DataRow[] rCheck = tblPO.Select("ItemCode='" + ItemCode + "'");
                    if (rCheck.Length == 0)
                    {
                        tblPO.Rows.Add(rowNew);
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return tblPO;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["VatPrcnt"] != null && row["VatPrcnt"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["VatPrcnt"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
                this.lblDocumentTotal.Text = GF.FormatNumeric(documentTotal.ToString(), "SumDec");
                this.lblTaxAmount.Text = GF.FormatNumeric(gstTotal.ToString(), "SumDec");
                this.lblSubTotal.Text = GF.FormatNumeric(subTotal.ToString(), "SumDec");
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        private string CheckDate()
        {
            if (this.txtDelDate.Text.Trim().Length > 0 && this.txtPODate.Text.Trim().Length > 0)
            {
                if (Utils.AppConstants.isDateTime(this.txtPODate.Text) && Utils.AppConstants.isDateTime(this.txtDelDate.Text))
                {
                    if (Utils.AppConstants.ConvertToDate(this.txtPODate.Text).Date > Utils.AppConstants.ConvertToDate(this.txtDelDate.Text).Date)
                    {
                        return "Delivery Date cannot earliar than PO Issue Date.";
                    }
                }
                else
                {
                    return "PO Issue Date or Expected Delivery Date is incorrect format.";
                }
            }
            else
            {
                return "PO Issue Date or Expected Delivery Date is not Blank.";
            }
            return string.Empty;
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvGRPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (!Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM)) grvGRPO.Columns[8].Visible = false; // Option Code

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value.Equals("C") || (ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO) == hdnBaseType.Value))
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscPrcnt = (TextBox)myRow.FindControl("txtDiscPrcnt");

                    DropDownList ddlModel = (DropDownList)myRow.FindControl("ddlModel");
                    DropDownList ddlProduct = (DropDownList)myRow.FindControl("ddlProduct");
                    DropDownList ddlColor = (DropDownList)myRow.FindControl("ddlColor");
                    DropDownList ddlOpt = (DropDownList)myRow.FindControl("ddlOpt");
                    DropDownList ddlWhs = (DropDownList)myRow.FindControl("ddlWhs");

                    if (ddlModel != null)
                    {
                        ddlModel.Enabled = false;
                        ddlModel.BackColor = System.Drawing.Color.Transparent;
                        ddlModel.BorderStyle = BorderStyle.None;
                    }

                    if (ddlProduct != null)
                    {
                        ddlProduct.Enabled = false;
                        ddlProduct.BackColor = System.Drawing.Color.Transparent;
                        ddlProduct.BorderStyle = BorderStyle.None;
                    }

                    if (ddlColor != null)
                    {
                        ddlColor.Enabled = false;
                        ddlColor.BackColor = System.Drawing.Color.Transparent;
                        ddlColor.BorderStyle = BorderStyle.None;
                    }

                    if (ddlOpt != null)
                    {
                        ddlOpt.Enabled = false;
                        ddlOpt.BackColor = System.Drawing.Color.Transparent;
                        ddlOpt.BorderStyle = BorderStyle.None;
                    }

                    if (ddlWhs != null)
                    {
                        ddlWhs.Enabled = false;
                        ddlWhs.BackColor = System.Drawing.Color.Transparent;
                        ddlWhs.BorderStyle = BorderStyle.None;                    
                    }

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                    }
                    if (txtDiscPrcnt != null)
                    {
                        txtDiscPrcnt.ReadOnly = true;
                        txtDiscPrcnt.BackColor = System.Drawing.Color.Transparent;
                        txtDiscPrcnt.BorderStyle = BorderStyle.None;
                    }
                }

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.btnAddItems.Enabled = false;
            }
            UpdatePrice();
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //if (!CheckValidData((DataTable)Session["PDN1Table"])) return;
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO), txtGRPONo.Text, hdnIsUpdate.Value.Equals("true"), dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            //try
            //{
            //    Transaction obj = new Transaction();
            //    string error = string.Empty;
            //    if (_isPO == "1")
            //    {
            //        //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
            //    }
            //    else
            //    {
            //        //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
            //    }
            //    if (error.Length == 0)
            //    {
            //        this.lblError.Text = "Operation complete successful!";
            //        DisableControl();
            //    }
            //    else
            //    {
            //        this.lblError.Text = error;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //}
            //this.lblError.Visible = true;
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Taxcode");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");
            dt.Columns.Add("PriceBefDi");
            //dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("Price");
            dt.Columns.Add("WhsCode");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("U_OptionCode");

            //dt.Columns.Add("SysNumber");
            //dt.Columns.Add("DistNumber");
            //dt.Columns.Add("InDate");
            //dt.Columns.Add("Notes");

            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("BaseType");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["LineNum"] = dr["LineNum"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Taxcode"] = dr["Taxcode"];
                    row["VatPrcnt"] = dr["VatPrcnt"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = dr["Quantity"];
                    row["OpenQty"] = dr["OpenQty"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    //row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["Price"] = dr["Price"]; // Price After Discount
                    row["WhsCode"] = dr["WhsCode"];
                    if (dtContent.Columns.Contains("U_OptionCode")) row["U_OptionCode"] = dr["U_OptionCode"];
                    row["LineTotal"] = dr["LineTotal"];

                    //if (dr.Table.Columns.Contains("DistNumber"))
                    //{
                    //    row["SysNumber"] = dr["SysNumber"];
                    //    row["DistNumber"] = dr["DistNumber"];
                    //    row["InDate"] = dr["InDate"];
                    //    row["Notes"] = dr["Notes"];
                    //}

                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadDefault()
        {
            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDelDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtPODate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtGRPONo.Text = 
            this.txtConpersonName.Text =
            this.txtVendorCode.Text = 
            this.txtVendorName.Text = 
            hdnBaseType.Value = string.Empty;
            // Binding data Buyer
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");

            dtContents = BuildContents(dtContents);
            BindData(dtContents);
        }

        protected void LoadData(String grpoId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = null;
            if (ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO) != NewDocType) // in-case is copy from
                returnDoc = ts.GetMarketingDocument_OpenStatus(NewDocType, grpoId, dbType);
            else returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, grpoId, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType); //grpoId = "1"; get default            

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];

            this.txtVendorName.Text = dr["CardName"].ToString();
            this.txtVendorCode.Text = dr["CardCode"].ToString();
            this.txtGRPONo.Text = dr["DocEntry"].ToString();
            this.lblStatus.Text = dr["DocStatus"].ToString();

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")) );
            txtPODate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")) );
            txtDelDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], new CultureInfo("es-US")) );
            txtRemarks.Text = dr["Comments"].ToString();

            // Binding data Buyer
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, dr["SlpCode"].ToString());

            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                if (NewDocType != ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO) )
                    SetScreenStatus("New");
                else SetScreenStatus("Update");
            }

            
            dtContents = BuildContents(returnDoc.Tables[1]);
            hdnBaseType.Value = NewDocType;

            foreach (DataRow row in dtContents.Rows)
            {
                updateRowTotalPrice(row, "");
                if (ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO) != NewDocType) //in this case is copy to
                {
                    row["BaseEntry"] = grpoId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                    row["Quantity"] = row["OpenQty"];
                }
            }
            BindData(dtContents);
            updateTableTotalPrice();
        }

        protected void ClearScreen()
        {
           
            // Binding data Buyer
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");

            dtContents = new DataTable(TblLineName);
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("LineNum");
            dtContents.Columns.Add("ItemCode");
            dtContents.Columns.Add("Taxcode");
            dtContents.Columns.Add("VatPrcnt");
            dtContents.Columns.Add("Dscription");
            dtContents.Columns.Add("U_Model");
            dtContents.Columns.Add("U_Color");
            //dtContents.Columns.Add("UomCode");
            dtContents.Columns.Add("Quantity");
            dtContents.Columns.Add("PriceBefDi");
            //dtContents.Columns.Add("DiscPrcnt");
            dtContents.Columns.Add("Price");
            dtContents.Columns.Add("WhsCode");
            dtContents.Columns.Add("U_OptionCode");
            dtContents.Columns.Add("LineTotal");

            //dtContents.Columns.Add("SysNumber");
            //dtContents.Columns.Add("DistNumber");
            //dtContents.Columns.Add("InDate");
            //dtContents.Columns.Add("Notes");

            dtContents.Columns.Add("BaseEntry");
            dtContents.Columns.Add("BaseLine");
            dtContents.Columns.Add("BaseType");
            
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDelDate.Text.ToString(ci);
            txtPODate.Text.ToString(ci); 

            txtGRPONo.Text =
            txtRemarks.Text =
            txtConpersonName.Text =
            txtVendorCode.Text = 
            txtVendorName.Text =
            hdnBaseType.Value = String.Empty; 

            this.lblSubTotal.Text = 
            this.lblTaxAmount.Text = 
            this.lblDocumentTotal.Text = "0";

            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAddItems.Visible = false;
                    btnSave.Visible = true;
                    btnCopyFrom.Visible = true;
                    btnCopyTo.Visible = false;
                    hdnIsUpdate.Value = "false";
                    break;

                case "Update":
                    hdnIsUpdate.Value = "true";
                    btnAddItems.Visible = true;
                    btnSave.Visible = true;
                    btnCopyFrom.Visible = true;
                    btnCopyTo.Visible = true;
                    break;

                case "Close":
                    btnAddItems.Visible = false;
                    btnSave.Visible = false;
                    hdnIsUpdate.Value = "false";
                    btnCopyFrom.Visible = true;
                    btnCopyTo.Visible = false;
                    break;
            }
        }

        private void BuildSRNT(ref DataTable dtSRNT, string DocType, string DocEntry, string DocLineNum,
                string ItemCode, string OptCode, string WhsCode, string DistNumber, string Notes, string KeyNumber, string YoP, string SysNumber, string InDate, double Quantity)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("DocType", typeof(System.Int32) );      // 13
                dtSRNT.Columns.Add("DocEntry", typeof(System.Int32) );     // Get from Incoming Payment No.
                dtSRNT.Columns.Add("DocLineNum", typeof(System.Int32));   // 1
                dtSRNT.Columns.Add("ItemCode", typeof(System.String));
                dtSRNT.Columns.Add("U_OptionCode", typeof(System.String) );
                dtSRNT.Columns.Add("WhsCode", typeof(System.String));      // 
                dtSRNT.Columns.Add("DistNumber", typeof(System.String));   // VIN Number
                dtSRNT.Columns.Add("Notes", typeof(System.String));        // Engine Number
                dtSRNT.Columns.Add("U_KeyNo", typeof(System.String));      // Key Number
                dtSRNT.Columns.Add("U_ProductionYear"); // Key Number
                dtSRNT.Columns.Add("SysNumber", typeof(System.String));    // Default
                dtSRNT.Columns.Add("InDate", typeof(System.String));       // Get default
                dtSRNT.Columns.Add("Quantity");     // 1
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["DocType"] = DocType;         // INV1
            drSRNT["DocEntry"] = String.IsNullOrEmpty(DocEntry) ? "0" : DocEntry;
            drSRNT["DocLineNum"] = String.IsNullOrEmpty(DocLineNum) ? "0" : DocLineNum;
            drSRNT["ItemCode"] = ItemCode;      // INV1
            drSRNT["U_OptionCode"] = OptCode;
            drSRNT["WhsCode"] = WhsCode;         // INV1
            drSRNT["DistNumber"] = DistNumber;   // VIN Number
            drSRNT["Notes"] = Notes;             // Engine Number
            drSRNT["U_KeyNo"] = KeyNumber;       // Key Number
            drSRNT["U_ProductionYear"] = YoP;    // Year of Production
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyyMMdd");
            drSRNT["Quantity"] = Quantity;       // INV1

            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData()
        {
            try
            {
                dtContents = (DataTable)Session["PDN1Table"];
                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series");
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("SlpCode");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");

                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true")) // Update
                {
                    drHeader["DocEntry"] =
                    drHeader["DocNum"] = int.Parse(txtGRPONo.Text);
                }
                else // Add new
                {
                    drHeader["Series"] = 11;
                    drHeader["DocStatus"] = "O";
                }

                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDelDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtPODate.Text).ToString("yyyyMMdd");
                drHeader["CardCode"] = txtVendorCode.Text;
                drHeader["CardName"] = txtVendorName.Text.Trim();
                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["SlpCode"] = ddlBuyer.SelectedValue;
                //dr["JrnlMemo"] = txtJournalRemark.Text;
                // UDF
                drHeader["U_ContactPerson"] = txtConpersonName.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;


                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                //dt.Columns.Add("UomCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("PriceBefDi");
                //dt.Columns.Add("DiscPrcnt");
                dt.Columns.Add("Price");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("LineTotal");
                dt.Columns.Add("U_OptionCode");
                //DataTable dtSRNT = null;
                if (!String.IsNullOrEmpty(hdnBaseType.Value))
                {
                    dt.Columns.Add("BaseEntry");
                    dt.Columns.Add("BaseLine");
                    dt.Columns.Add("BaseType");
                }

                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        if (hdnIsUpdate.Value.Equals("true")) row["DocEntry"] = int.Parse(txtGRPONo.Text);
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        
                        row["Dscription"] = dr["Dscription"];
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        //row["UomCode"] = dr["UomCode"];
                        row["Quantity"] = dr["Quantity"];
                        row["PriceBefDi"] = dr["PriceBefDi"];
                        //row["DiscPrcnt"] = dr["DiscPrcnt"];
                        row["Price"] = dr["Price"]; // Price After Discount
                        row["WhsCode"] = dr["WhsCode"];
                        row["LineTotal"] = dr["LineTotal"];
                        row["U_OptionCode"] = dr["U_OptionCode"];

                        if (!String.IsNullOrEmpty(hdnBaseType.Value))
                        {
                            row["BaseEntry"] = dr["BaseEntry"];
                            row["BaseLine"] = dr["BaseLine"];
                            row["BaseType"] = dr["BaseType"];
                        }
                        //string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                        //if (!GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["ItemCode"].ToString()).Equals("104"))
                        //    BuildSRNT(ref dtSRNT, dr["ItemCode"].ToString(), dr["SysNumber"].ToString(), dr["DistNumber"].ToString(), dr["Indate"].ToString(),
                        //        dr["Notes"].ToString(), double.Parse(dr["Quantity"].ToString()), "01", ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO), txtGRPONo.Text, liNo.ToString());

                        dt.Rows.Add(row);
                        liNo++;
                    }
                }

                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "LineTotal" }; // Columns need to reset format numeric
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());

                DataTable dtSRNT = (DataTable)Session["tblSRNT"];
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow[] rDocLineNum = dtSRNT.Select("ItemCode='" + dr["ItemCode"].ToString() + "'");
                    if (rDocLineNum.Length > 0)
                    {
                        for (int i = 0; i < rDocLineNum.Length; i++)
                        {
                            rDocLineNum[i]["DocLineNum"] = dr["LineNum"];
                            rDocLineNum[i]["WhsCode"] = dr["WhsCode"];
                        }
                    }
                }
                if (dtSRNT != null) ds.Tables.Add(dtSRNT.Copy());

                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS( ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void updateTableTotalPrice()
        {
            double orderTotalBeforeDiscount = 0.0;
            double orderTotal = 0.0;
            double taxTotal = 0.0;
            foreach (DataRow row in dtContents.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    double taxRate = GF.Object2Double( GF.ResetFormatNumeric( row["VatPrcnt"].ToString()), "RateDec");
                    if (taxRate == 0) taxRate = 10;
                    double tax = total * taxRate / 100;
                    orderTotalBeforeDiscount += total;
                    taxTotal += tax;
                }
            }

            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");
            orderTotal = orderTotalBeforeDiscount + taxTotal;
            this.lblDocumentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double( GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            //discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") )
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            //if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("Quantity"))
            //    row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");
            
        }

        /*private bool CheckValidData(DataTable dtPDN1)
        {
            bool smooth = true;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            foreach (DataRow dr in dtPDN1.Rows)
            {
                if (GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["ItemCode"].ToString()).Equals("104")) continue;
                if(dr["DistNumber"].ToString().Equals(""))
                {
                    this.lblError.Text = " VIN Number cannot be empty. Please input VIN Number for '" + dr["ItemCode"].ToString() + "' item.";
                    this.lblError.Visible = true;
                    smooth = false;
                    break;
                }
                if (dr["Notes"].ToString().Equals(""))
                {
                    this.lblError.Text = " Engine Number cannot be empty. Please input Engine Number for '" + dr["ItemCode"].ToString() + "' item.";
                    smooth = false;
                    break;                
                }
            }
            return smooth;
        }*/

        protected void btnCopyTo_Click(object sender, EventArgs e)
        {
            Response.Redirect(TargetPageUrl + "?base_type=" + ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO) + "&base_entry=" + txtGRPONo.Text);
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsGRPONo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER, 
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.SALES,
                ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO), 
                TblHeaderName, HeaderKeyName
            );
            if (txtGRPONo.Text.CompareTo(lsGRPONo) != 0) Response.Redirect(CurrentPageUrl + "?grpo_id=" + lsGRPONo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label lblModel = (Label)row.FindControl("lblModel");
                lblModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label lblProduct = (Label)row.FindControl("lblProduct");
                    lblProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label lblProduct = (Label)row.FindControl("lblProduct");
                lblProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label lblColor = (Label)row.FindControl("lblColor");
                lblColor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlOpt_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlOpt = (DropDownList)row.FindControl("ddlOpt");
                HiddenField hdnOpt = (HiddenField)row.FindControl("hdnOpt");
                if (hdnOpt != null && !string.IsNullOrEmpty(hdnOpt.Value))
                {
                    hdnOpt.Value = ddlOpt.SelectedValue;
                    DataTable tblPDN1 = (DataTable)Session["PDN1Table"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    DataRow[] rowUpdate = tblPDN1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0) rowUpdate[0]["U_OptionCode"] = hdnOpt.Value;
                    BindData(tblPDN1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlWhs_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlWhs = (DropDownList)row.FindControl("ddlWhs");
                if (ddlWhs.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a warehouse');", true);
                    ddlWhs.Focus();
                    return;
                }

                HiddenField hdnWhsCode = (HiddenField)row.FindControl("hdnWhsCode");
                if (hdnWhsCode != null && !string.IsNullOrEmpty(hdnWhsCode.Value))
                {
                    hdnWhsCode.Value = ddlWhs.SelectedValue;
                    DataTable tblPDN1 = (DataTable)Session["PDN1Table"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    DataRow[] rowUpdate = tblPDN1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0) rowUpdate[0]["WhsCode"] = hdnWhsCode.Value;
                    BindData(tblPDN1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblPDN1 = (DataTable)Session["PDN1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");
            DropDownList ddlOpt = (DropDownList)row.FindControl("ddlOpt");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtVendorCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.SALES);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblPDN1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["U_OptionCode"] = ddlOpt.SelectedValue;

                            rowUpdate[0]["Quantity"] = 1;

                            //rowUpdate[0]["PriceBefDi"] = drDefaultLine["UnitPrice"];
                            //rowUpdate[0]["DiscPrcnt"] = drDefaultLine["Discount"];
                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["PriceAfDi"];
                            rowUpdate[0]["TaxCode"] = drDefaultLine["TaxCode"];
                            rowUpdate[0]["VatPrcnt"] = drDefaultLine["TaxRate"];
                            rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                        }
                    }
                }
                else
                {
                    rowUpdate = tblPDN1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["U_OptionCode"] = ddlOpt.SelectedValue;

                    rowUpdate[0]["Quantity"] = 1;

                    
                    //rowUpdate[0]["DiscPrcnt"] = 0;
                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["TaxCode"] = string.Empty;
                    rowUpdate[0]["VatPrcnt"] = 0;
                    rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                }
                BindData(tblPDN1);
            }
        }

        private DataTable datatable4Exp()
        {
            DataTable tblPDN1 = (DataTable)Session["PDN1Table"];
            DataTable dtRecords = new DataTable();
            dtRecords.Columns.Add(new DataColumn("Model", typeof(System.String) ));             // 0
            dtRecords.Columns.Add(new DataColumn("Product", typeof(System.String)));            // 1
            dtRecords.Columns.Add(new DataColumn("Color", typeof(System.String)));              // 2
            dtRecords.Columns.Add(new DataColumn("Item", typeof(System.String)));               // 3
            dtRecords.Columns.Add(new DataColumn("Option Code", typeof(System.String)));        // 4
            dtRecords.Columns.Add(new DataColumn("Whse Code", typeof(System.String)));          // 5
            dtRecords.Columns.Add(new DataColumn("VIN Number", typeof(System.String)));         // 6
            dtRecords.Columns.Add(new DataColumn("Engin Number", typeof(System.String)));       // 7
            dtRecords.Columns.Add(new DataColumn("Key Number", typeof(System.String)));         // 8
            dtRecords.Columns.Add(new DataColumn("Year of Production", typeof(System.String))); // 9

            DataRow dr = null;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            foreach (DataRow row in tblPDN1.Rows)
            {
                if (GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), row["ItemCode"].ToString()).Equals("104")) continue;
                string lsQty = row["Quantity"].ToString();
                int liQty = int.Parse(string.IsNullOrEmpty(lsQty) ? "0" : lsQty.Split('.')[0]);

                if (liQty == 1)
                {
                    dr = dtRecords.NewRow();
                    dr["Model"] = row["U_Model"];
                    dr["Product"] = row["U_Product"];
                    dr["Color"] = row["U_Color"];
                    dr["Item"] = row["ItemCode"];
                    dr["Option Code"] = row["U_OptionCode"];
                    dr["Whse Code"] = row["WhsCode"];
                    dtRecords.Rows.Add(dr);
                }
                else if(liQty > 1)
                {
                    for (int i = 0; i < liQty; i++)
                    {
                        dr = dtRecords.NewRow();
                        dr["Model"] = row["U_Model"];
                        dr["Product"] = row["U_Product"];
                        dr["Color"] = row["U_Color"];
                        dr["Item"] = row["ItemCode"];
                        dr["Option Code"] = row["U_OptionCode"];
                        dr["Whse Code"] = row["WhsCode"];
                        dtRecords.Rows.Add(dr);
                    }
                }
            }
            return dtRecords;
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbPDN1 = (DataTable)Session["PDN1Table"];
            DataRow rowNew = tbPDN1.NewRow();
            rowNew["No"] = (tbPDN1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["U_OptionCode"] = dtOpt.Rows.Count > 0 ? dtOpt.Rows[0]["Code"].ToString() : string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["PriceBefDi"] = 0;
            //rowNew["DiscPrcnt"] = 0;
            //rowNew["PriceBefDi"] = 0;
            rowNew["TaxCode"] = string.Empty;
            rowNew["VatPrcnt"] = 0;
            rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
            tbPDN1.Rows.Add(rowNew);
            BindData(tbPDN1);
        }

        private bool ImportValidation()
        {

            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if (!lsFileExtension.Equals(".csv"))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!ImportValidation()) return;
            // Reading .csv file
            string errMsg = GF.ReadFile(this.FileUploadControl.PostedFile.InputStream);
            if (string.IsNullOrEmpty(errMsg))
            {
                ImportData();
            }
            else
            {
                Session["errorMessage"] = errMsg;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
            }
        }

        private void ImportData()
        {
            DataTable tblSRNT = null;
            for (int x = 1; x < GF.FileLines.Count; x++)
            {
                string[] rowData = GF.FileLines[x].ToString().Split(',');
                BuildSRNT(ref tblSRNT, ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO), "", "", 
                    rowData[3], rowData[4], rowData[5], rowData[6], rowData[7], rowData[8], rowData[9], "", DateTime.Now.ToString("dd/MM/yyyy"), 1);
            }

            Session["tblSRNT"] = tblSRNT;
        }

        protected void btnGetTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = datatable4Exp();

                if (dt != null)
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=GRPO.csv");
                    Response.ContentType = "text/csv";
                    int iColCount = dt.Columns.Count;

                    for (int i = 0; i < iColCount; i++)
                    {
                        Response.Write("\"" + dt.Columns[i] + "\"");
                        if (i < iColCount - 1)
                        {
                            Response.Write(",");
                        }
                    }

                    Response.Write(Environment.NewLine);
                    // Now write all the rows.
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        for (int i = 0; i < iColCount; i++)
                        {
                            if (!Convert.IsDBNull(dt.Rows[x][i])) Response.Write("\"" + dt.Rows[x][i].ToString() + "\"");
                            if (i < iColCount - 1) Response.Write(",");
                        }
                        Response.Write(Environment.NewLine);
                    }
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

    }
}